<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/11 0011
 * Time: 15:36
 */

namespace Cuke\Controllers;


use Cuke\Http\ControllerBase;
use Cuke\Http\Response;
use Cuke\Models\CukeAdmin;
use Cuke\Models\CukeGroup;
use Cuke\Services\GroupService;
use  Cuke\Library\Paginator\PaginatorArray;

/**
 * 接口分组管理
 * @package Cuke\Controllers
 */
class GroupController extends ControllerBase
{
    public function listAction()
    {

        $page_index = intval($this->request->getQuery('page',null,1));

        $groupResult = GroupService::getInstance()->getGroupList($page_index);
        $paginator = new PaginatorArray([
            'data'          => $groupResult->lists,
            'limit'         => self::PageSize,
            'current'          => $page_index,
            'total_items'   => $groupResult->total_count,
            'href'          => $this->url->get('group/list'),
            'params'        => []
        ]);

        $this->view->setVar('Model',$paginator);
    }

    /**
     * 添加或编辑分组
     */
    public function editAction()
    {
        $user_id = $this->isSuperAdministrator() ? null : $this->member->user_id;

        $group_code = trim($this->dispatcher->getParam('group_code'));
        $group = new CukeGroup();
        //如果是post标识保存分组信息
        if($this->request->isPost()){
            $this->view->disable();
            $group_code = trim($this->request->getPost('groupCode'));
            $groupName = trim($this->request->getPost('groupName'));
            $status = intval($this->request->getPost('status'));
            $description = trim($this->request->getPost('description'));
            $trafficValue = max(intval($this->request->getPost('trafficValue')),0);

            //如果分组不为空，则需要校验是否有权限
            if(empty($group_code) === false){
                $group = GroupService::getInstance()->getGroupDetailed($group_code,$user_id);
                if(empty($group)){

                    $this->response->setJsonContent(['error_code' => 50001,'message' => '分组不存在或没有权限'])->send();
                    return;
                }
                //检查除当前分组之外是否存在指定名称的分组
                if(GroupService::getInstance()->existGroupByName($groupName,$this->member->user_id,[$group_code])){
                    $this->response->setJsonContent(['error_code' => 50003,'message' => '分组名称已被占用'])->send();
                    return;
                }
                $group->update_id = $this->member->user_id;
            }else{
                //检查分组名称是否被占用
                if(GroupService::getInstance()->existGroupByName($groupName,$this->member->user_id)){
                    $this->response->setJsonContent(['error_code' => 50003,'message' => '分组名称已被占用'])->send();
                    return;
                }
                $group->create_at = date('Y-m-d H:i:s');
                $group->create_id = $this->member->user_id;
                $group->group_code = str_replace('-','',$this->random->uuid());

            }

            $group->group_name = $groupName;
            $group->status = $status;
            $group->description = $description;
            $group->user_id = $this->member->user_id;
            $group->traffic_value = $trafficValue;

            //如果保存成功
            if($group->save()){
                $this->response->setJsonContent(['error_code' => 0,'message' => '保存成功','data' => $group])->send();
                return;
            }else{
                $message = $group->getMessage();
                if($message){
                    $message = $message->getMessage();
                }else{
                    $message = '保存失败';
                }
                $this->response->setJsonContent(['error_code' => 50002,'message' => $message])->send();
                return;
            }
        }

        if(empty($group_code) === false){
            $group = GroupService::getInstance()->getGroupDetailed($group_code,$user_id);
        }

        $this->view->setVar('Model',$group);

    }

    public function detailAction()
    {
        $user_id = $this->isSuperAdministrator() ? null : $this->member->user_id;

        $group_code = trim($this->dispatcher->getParam('group_code'));

        if(empty($group_code)){
            $this->dispatcher->forward([ 'controller' => 'Errors', 'action'     => 'show404']);
            return;
        }
        $group = new CukeGroup();
        if(empty($group_code) === false){
            $group = GroupService::getInstance()->getGroupDetailed($group_code,$user_id);
            if(!$group){
                $this->dispatcher->forward([ 'controller' => 'Errors', 'action'     => 'show404']);
                return;
            }
        }
        $user = CukeAdmin::findFirst($group->user_id);

        $this->view->setVar('User',$user);

        $this->view->setVar('Model',$group);
    }
}